import { useEffect, useRef, useState } from 'react';

interface ISvg {
	src: string;
	style?: {
		[key: string]: string;
	};
}

export default function Svg(props: ISvg) {
	const { src, style = {} } = props;
	const [svgText, setSvgText] = useState<any>(null);
	const svgBox = useRef<HTMLDivElement>(null);

	useEffect(() => {
		if (!src) return;

		const reader = new FileReader();
		reader.onload = (res) => {
			const text = res.target!.result as string;
			setSvgText(text);
			const svgEl = svgBox.current!.children[0] as SVGElement;
			if (svgEl) {
				Object.keys(style).forEach((key: any) => {
					svgEl.style[key] = style[key];
				});
			}
		};

		fetch(src)
			.then((res) => res.blob())
			.then((blob) => {
				reader.readAsText(blob);
			});
	}, [src]);

	return (
		<div
			ref={svgBox}
			dangerouslySetInnerHTML={{ __html: svgText }}
			style={{ display: 'inline-block' }}
		/>
	);
}
